﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Reflection;
using System.Text;
using XuanXiang.Infrastructure.Attr;
using XuanXiang.Infrastructure.Tools;
using XuanXiang.Service.Interface;
using static System.Net.Mime.MediaTypeNames;

namespace XuanXiang.Api.Admin.Filters
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class Right_Filter : Base_Filter
    {
        private readonly I_System_Service _system_Service;

        public Right_Filter(I_Login_Service login_Service,I_System_Service system_Service) : base(login_Service)
        {
            _system_Service = system_Service;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var action = context.ActionDescriptor as ControllerActionDescriptor;    
            var attr = action!.MethodInfo.GetCustomAttribute<Right_Attribute>();//获取权限特性/属性
            if (attr != null) {
                //判断用户是否有该接口指定的地址的权限
                var code = context.HttpContext.User.Identity?.Name;//NAME=Code 
                //获取当前登录的用户
                var user = Get_Users(code!);
                if (user == null) {
                    context.Result = new ForbidResult();//403
                }

                var urls = attr.urls!.Split(",").ToList();
                if (!_system_Service.Check_Right(user.id,urls)) {
                    context.Result = new ForbidResult();
                }
            }

            base.OnActionExecuting(context);
        }
    }
}
